from __future__ import print_function
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import Template, Context
from django.core.urlresolvers import reverse
from django.template.loader import get_template
from django.forms.formsets import formset_factory

import requests
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
from .forms import *
from .models import *
import datetime
import json

def index(request):
	t = get_template('eMHubCalendar.html')
	return render(request,'eMHubCalendar.html')

def get_credentials():

	"""Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """

	SCOPES = 'https://www.googleapis.com/auth/calendar'
	CLIENT_SECRET_FILE = 'client_secret.json'
	APPLICATION_NAME = 'eMHub'
	home_dir = os.path.expanduser('~')
	credential_dir = os.path.join(home_dir, '.credentials')
	if not os.path.exists(credential_dir):
	    os.makedirs(credential_dir)
	credential_path = os.path.join(credential_dir,
	                               'calendar-python-quickstart.json')

	store = oauth2client.file.Storage(credential_path)
	credentials = store.get()
	if not credentials or credentials.invalid:
	    flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
	    flow.user_agent = APPLICATION_NAME
	    if flags:
	        credentials = tools.run_flow(flow, store, flags)
	    else: # Needed only for compatibility with Python 2.6
	        credentials = tools.run(flow, store)
	    print('Storing credentials to ' + credential_path)
	return credentials

# def getEvents(request):
# 	credentials = get_credentials()
# 	http = credentials.authorize(httplib2.Http())
# 	service = discovery.build('calendar', 'v3', http=http)

# 	now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
# 	eventsResult = service.events().list(
# 		calendarId='primary', timeMin=now, maxResults=100, singleEvents=True,
# 		orderBy='startTime').execute()
# 	events = eventsResult.get('items', [])

# 	if not events:
# 		print('No upcoming events found.')
# 	for event in events:
# 		start = event['start'].get('dateTime', event['start'].get('date'))
# 		print(start, event['summary'])
# 	return events
	
def get_event(request):
	credentials = get_credentials()
	http = credentials.authorize(httplib2.Http())
	service = discovery.build('calendar', 'v3', http=http)

	if request.method == "POST":
		form = getEventForm(request.POST)
		if form.is_valid():
			eventId = form.cleaned_data['eventId']
			event = service.events().get(calendarId='l9am6s2f1j5b11cja3ipnv4djk@group.calendar.google.com', eventId=eventId).execute()
			order = ['status', 'description', 'location', 'creator', 'created', 'start', 'end', 'htmlLink']
			temp = []
			try:
				summary = event['summary']
			except (KeyError):
				return(request, 'view_event.html', {'summary': summary, 'error_message': "No Title Found"})

			for item in order:
				try:
					temp.append((item,event[item]))
				except (KeyError):
					continue
					
			return render(request, 'view_event.html', {'summary': summary, 'items': temp})
	else:
		form = getEventForm()
	return render(request, 'get_event.html', {'geteventform': form})		

def date_handler(obj):
    return obj.isoformat() if hasattr(obj, 'isoformat') else obj

def create_event(request):
	credentials = get_credentials()
	http = credentials.authorize(httplib2.Http())
	service = discovery.build('calendar', 'v3', http=http)

	if request.method == "POST":
		form = createEventForm(request.POST)
		if form.is_valid():
			event = {
			'summary': form.cleaned_data['summary'],
			'location': form.cleaned_data['location'],
			'description': form.cleaned_data['description'],
			'start': {
				'date': form.cleaned_data['start'],
				# 'dateTime': str(json.dumps(form.cleaned_data['start'], default=date_handler)),
				'timezone': form.cleaned_data['timeZone'],
			},
			'end': {
				'date': form.cleaned_data['end'],
				# 'dateTime': str(json.dumps(form.cleaned_data['end'], default=date_handler)),
				'timezone': form.cleaned_data['timeZone'],
			},
			}
			service.events().insert(calendarId='l9am6s2f1j5b11cja3ipnv4djk@group.calendar.google.com', body=event).execute()
			return HttpResponseRedirect(reverse('gcalendar:index'))
	else:
		form = createEventForm()
	return render(request, 'create_event.html', {'form': form})		



def createCalendar(request):
	credentials = get_credentials()
	http = credentials.authorize(httplib2.Http())
	service = discovery.build('calendar', 'v3', http=http)
	
	calendar = {
        'summary': 'calendarSummary',
        'timeZone': 'America/New_York'
    }
    
	created_calendar = service.calendars().insert(body=calendar).execute()
	print(created_calendar['id'])
	return created_calendar
	
def getCalendar(request,id):
	credentials = get_credentials()
	http = credentials.authorize(httplib2.Http())
	service = discovery.build('calendar', 'v3', http=http)
	
	calendar = service.calendars().get(calendarId=id).execute()
	print(calendar)
	return

